package cn.beforedark.yygh.cmn.service.impl;

import cn.beforedark.yygh.cmn.mapper.DictMapper;
import cn.beforedark.yygh.cmn.service.DictExcelDtoListener;
import cn.beforedark.yygh.cmn.service.DictService;
import cn.beforedark.yygh.model.cmn.Dict;
import cn.beforedark.yygh.vo.cmn.DictExcelVo;
import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;


@Service
public class DictServiceImpl extends ServiceImpl<DictMapper, Dict> implements DictService {


    @Cacheable(value = "dict", key = "'getChildListByPid:'+#pid")
    @Override
    public List<Dict> getChildListByPid(Long pid) {

        QueryWrapper<Dict> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_id", pid);
        List<Dict> dictList = baseMapper.selectList(wrapper);
        for (Dict dict : dictList) {
            dict.setHasChildren(hasChild(dict.getId()));
        }
        return dictList;
    }

    @Override
    public void exportExcel(HttpServletResponse response) {
        try {
            List<Dict> x = baseMapper.selectList(null);
            List<DictExcelVo> y = new ArrayList<>(x.size());
            // x -> y ,   y是最终excel的内容
            for (Dict dict : x) {
                DictExcelVo dictEeVo = new DictExcelVo();
                BeanUtils.copyProperties(dict, dictEeVo);
                y.add(dictEeVo);
            }
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            // .replaceAll("\\+", "%20");我也不知道在干嘛，哪来的空格
            String fileName = URLEncoder.encode("数据字典", "UTF-8").replaceAll("\\+", "%20");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
            EasyExcel.write(response.getOutputStream(), DictExcelVo.class).sheet("数据字典").doWrite(y);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }

    @Override
    @Transactional
    @CacheEvict(value = "dict", allEntries = true)
    public void importExcel(MultipartFile file) {
        try {

            EasyExcel.read(file.getInputStream(),
                            DictExcelVo.class,
                            new DictExcelDtoListener(baseMapper))
                    .sheet(0).doRead();

        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public String getNameByDictCodeAndValue(String dictCode, Long value) {

        String error = "";

        if (StringUtils.isEmpty(dictCode)) {
            Dict dict = baseMapper.selectOne(new QueryWrapper<Dict>().eq("value", value));
            return dict == null ? error : dict.getName();
        } else {
            QueryWrapper<Dict> wrapper = new QueryWrapper<>();
            wrapper.eq("dict_code",dictCode);
            Dict parent = baseMapper.selectOne(wrapper);

            if(parent == null){
                return error;
            }

            QueryWrapper<Dict> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("parent_id",parent.getId());
            queryWrapper.eq("value",value);
            Dict son = baseMapper.selectOne(queryWrapper);

            if(son == null){
                return error;
            }
            return son.getName();
        }
    }

    @Override
    public Dict getByDictCode(String dictCode) {
        return baseMapper.selectOne(new QueryWrapper<Dict>().eq("dict_code", dictCode));
    }


    // 判断是否有子节点
    private boolean hasChild(Long pid) {
        QueryWrapper<Dict> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_id", pid);
        Integer count = baseMapper.selectCount(wrapper);
        return count != null && count > 0;
    }


}
